/**
 * 
 */
package com.pojocreator.common;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Anubhab
 * 
 */
public class AccessProperties {

	private static final Log log = LogFactory.getLog(AccessProperties.class);
	private static Properties props = null;
	private static FileInputStream fileInput = null;
	private static String propLocation = null;
	
	static {
		props = new Properties();
		propLocation = "resources/pojoFormation.properties";
	}

	/**
	 * This method loads the properties file, gets the desired field
	 * and returns the field value
	 * @param queryName
	 * @return value
	 */
	public static String getValueFromProps(String queryName) {
		String value = null;
		try {
			loadProperties();
			value= readField(queryName);
		} finally {
			unLoadProperties();
		}
		return value;
	}

	/**
	 * This method loads the properties file 
	 */
	public static void loadProperties() {
		log.debug("Loading properties from ["+propLocation+"]");
		try {
			fileInput = new FileInputStream(propLocation);
			props.load(fileInput);
		} catch (FileNotFoundException e) {
			log.info("The properties file for the standalone was not found");
			log.error("",e);
		} catch (IOException e) {
			log.info("Error occurred while access the properties file");
			log.error("",e);
		}
	}

	/**
	 * This method reads fields and returns the value for the property key
	 * specified from the pre-loaded properties file
	 * @param fieldName
	 * @return value
	 */
	public static String readField(String fieldName) {
		if(props==null){
			log.error("PROPERTIES FILE WAS NOT LOADED..");
			return null;
		}
		return props.getProperty(fieldName);
	}

	public static void unLoadProperties() {
		try {
			fileInput.close();
		} catch (IOException e) {
			log.info("Error occured while closing the properties file");
			log.error("",e);
		}
	}
}
